namespace Eno.Application.Services;

using System;
using System.Security.Cryptography;

public class PasswordService
{
    private const int SaltSize = 16; // bytes
    private const int HashSize = 20; // bytes
    private const int Iterations = 10000; // 迭代次数

    // 生成密码的哈希（注册/改密时用）
    public string HashPassword(string password, out string salt)
    {
        // 生成盐
        var saltBytes = new byte[SaltSize];
        using (var rng = RandomNumberGenerator.Create())
        {
            rng.GetBytes(saltBytes);
        }
        salt = Convert.ToBase64String(saltBytes);
        // 创建哈希
        using (var pbkdf2 = new Rfc2898DeriveBytes(password, saltBytes, Iterations, HashAlgorithmName.SHA256))
        {
            return Convert.ToBase64String(pbkdf2.GetBytes(HashSize));
        }
    }

    // 校验密码时用：传入已有salt
    public string HashPassword(string password, string salt)
    {
        var saltBytes = Convert.FromBase64String(salt);
        using (var pbkdf2 = new Rfc2898DeriveBytes(password, saltBytes, Iterations, HashAlgorithmName.SHA256))
        {
            return Convert.ToBase64String(pbkdf2.GetBytes(HashSize));
        }
    }
}